import { createRouter, createWebHashHistory } from 'vue-router'
import Layout from '@/views/Layout/index.vue'
import store from '@/store'

const routes = [
  {
    path: '/Test', component: () => import('@/views/Test/index.vue')
  },
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/', component: () => import('@/views/Home/index.vue') },
      { path: '/category/:id', component: () => import('@/views/Category/index.vue') },
      { path: '/product/:id', component: () => import('@/views/Goods/index.vue') },
      { path: '/cart', component: () => import('@/views/Cart/index.vue') },
      { path: '/settlement', component: () => import('@/views/Settlement/index.vue') },
      { path: '/Pay', component: () => import('@/views/Pay/index.vue') },
      { path: '/Pay/callback', component: () => import('@/views/Pay/callback.vue') },
      {
        path: '/Member',
        component: () => import('@/views/Member/Layout/index.vue'),
        children: [
          { path: '', component: () => import('@/views/Member/Home/index.vue') },
          { path: 'order', component: () => import('@/views/Member/Order/index.vue') }
        ]
      }
    ]
  },
  { path: '/Login', component: () => import('@/views/Login/index.vue') },
  {
    path: '/login/callback',
    component: () => import('@/views/Login/callback')
  }
]

const router = createRouter({
  // VueRouter官方文档 进阶-滚动行为
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      // console.log('以前滚动的位置',savedPosition);
      return savedPosition
    } else {
      // 滚动到顶部
      // vue2的坐标{x，y}
      // vue3的坐标是{top,left}
      return { behavior: 'smooth', top: 0 }
    }
  },
  // 使用hash方式实现路由
  history: createWebHashHistory(),
  // 配置路由规则，写法和之前一样
  routes
})

// to      去哪里
// from    从哪里来
// next    方向函数
// 路由设计  需要用户登录后才能访问的页面，统一都是 /member 开头
router.beforeEach((to, from, next) => {
  if (to.path.startsWith('/member') && !store.state.user.profile.token) {
    next('/login?redirectUrl=' + to.fullPath)
  } else {
    next()
  }
})

export default router
